# FILE: CSEBroker.py
# DESC: obtains search results from CSE server 
#

import urllib

from web.service.HttpReader import HttpReader
from web.service.CSEParser import CSEParser
from lbc.models import *
from lbc.LBCSearchResult import LBCSearchResult
from infra.logging import logger


#GOOGLE_CSE_URL = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&hl=sk&cx=%s&q=%s&key=notsupplied&start=%s'
GOOGLE_CSE_URL = 'http://www.google.com/cse?cref=%s&q=%s&sa=Search&hl=%s'

	
class CSEBroker:
	lbcBrokers_ = {}
	
	def __init__(self, searchEngine):				
		self.searchEngine_ = searchEngine
		self.cseParser_ = CSEParser()
		
		
	def search(self, query, lbcBrokers, language = 'sk'):
		return self.fetch__(GOOGLE_CSE_URL % (urllib.quote_plus(self.searchEngine_.getSpecUrl()), 
														  urllib.quote_plus(query.encode('utf-8')), 
														  language), lbcBrokers)


	def fetchPage(self, page, lbcBrokers):
		return self.fetch__('http://www.google.com%s' % page, lbcBrokers)				
			
			
	def fetch__(self, url, lbcBrokers):
		searchResults = []
		log = logger.getLogger()
						
		try:
			httpReader = HttpReader()
			response = httpReader.read(url, encode = True)
		
			(resultStat, results, navBar) = self.cseParser_.parse(response)
			
			for result in results:
				try:
					searchResults.append(LBCSearchResult(result, findOrganizationByUrl(result['url'])))							
				except Organization.DoesNotExist:				
					for lbcBroker in lbcBrokers:
						if lbcBroker.acceptUrl(result['url']):								
							try:
								searchResults.append(LBCSearchResult(result, lbcBroker.findOrganization(result)))
							except Organization.DoesNotExist:
								pass
			
			return (resultStat, searchResults, navBar)
			
		except Exception, e:
			log.error('An exception has been raised, reason: %s' % e)
			raise
		
		
